<template>
  <el-container style="display: flex; justify-content: center;align-items: center;height: 60vh; ">
    <div style="display: flex; justify-content: center;">
      <el-card class="box-card">
        <div class="clearfix">
          <span>比赛项目填报</span>
        </div>
        <div class="body">
        <el-form :model="eventForm" label-width="80px" class="event-form">
              <el-form-item label="项目名称" >
                <el-select v-model="eventForm.projectName" placeholder="请选择">
                  <el-option v-for="project in projects" :key="project.id" :label="project.projectName"
                    :value="project.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="参赛人员" >
                <el-select v-model="eventForm.participants" multiple :disabled="!eventForm.projectName"
                  placeholder="请选择">
                  <el-option v-for="staff in staffs" :key="staff.id"
                    :label="`(序号${staff.id})${staff.userName}:${staff.sex}`" :value="staff.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="套路名称" >
                <el-input v-model="eventForm.routineName"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="saveAndContinue"
                  style="width: 400px;">提交本项目的人员填报</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="success" @click="showConfirmDialog"
                  style="width: 400px; ">
                  前往项目难度申报
                </el-button>
              </el-form-item>
              <el-dialog title="确认提示" v-model="confirmDialogVisible" width="30%" @confirm="handleConfirm"
                @cancel="handleCancel">
                <span style="font-size: 18px;">请确认您已经完成本页面的项目人员填报，将前往难度申报页面。</span>
                <span class="dialog-footer">
                  <el-button @click="handleCancel">取 消</el-button>
                  <el-button type="primary" @click="handleConfirm">确 定</el-button>
                </span>
              </el-dialog>
        </el-form>
      </div>
      </el-card>
    </div>
  </el-container>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useTeamStore } from '../store/teamgroupid.js';
import { useMatchIdStore } from '../store/matchid.js';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const matchStore = useMatchIdStore();

const teamStore = useTeamStore();

const matchid = matchStore.matchId;

const staffs = teamStore.staffs;

const token = localStorage.getItem('userToken');

const confirmDialogVisible = ref(false);

const routineId = ref('');

const eventForm = ref({
  projectName: null,
  eventName: '',
  routineName: '',
  participants: []
});

const eventgroup = ref({
  groupName: ''
});

const projects = ref([]);
// 监听项目名称的变化，如果为空，则清空参赛人员列表
watch(() => eventForm.value.projectName, (newProjectName) => {
  if (newProjectName === null) {
    ElMessage.error('请先选择一个项目');
    eventForm.value.participants = [];
  }
});

// 获取项目列表
onMounted(async () => {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    projects.value = response.data.project;
  } catch (error) {
    console.error('Failed to fetch projects:', error);
  }
});


function showConfirmDialog() {  
  confirmDialogVisible.value = true; // 显示弹窗
}
async function handleConfirm() {  
  // 提交套路表单
  if (!eventForm.value.routineName) {
    ElMessage.error('请输入套路名称');
    return;
  }
  const routine = {
    memo: eventForm.value.routineName,
    teamId: teamStore.teamGroupId,
    projectId: eventForm.value.projectName,
    userId: eventForm.value.participants
  };

  try {
    const response = await axios.post(`http://back1.idcfengye.com:15173/routine/teamproject`, routine, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    routineId.value = response.data.data;
  } catch (error) {
    if (error.response && error.response.status !== 200) {
      ElMessage.error(`填报失败: ${error.response.data.msg}`);
      return;
    }
  }

  try {
    // 为每个参与者创建数据对象并发送POST请求
    for (const participantId of eventForm.value.participants) {
      const data = {
        routineid: routineId.value,
        teamId: teamStore.teamGroupId,
        projectId: eventForm.value.projectName,
        userId: participantId
      };

      // 发送POST请求
      const response = await axios.post(`http://back1.idcfengye.com:15173/teamgroup/memo`, data, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.status === 200 || response.data.success) {
        confirmDialogVisible.value = false; // 隐藏弹窗  
        ElMessage.success('填报成功');
      }
    }
  } catch (error) {
    if (error.response && error.response.status !== 200) {
      ElMessage.error(`填报失败: ${error.response.data.msg}`);
    }
  }

router.push({ path: '/home/Provisionsdeclaration', query: { routineid: routineId.value } });
}

function handleCancel() {
  confirmDialogVisible.value = false; // 隐藏弹窗    
}

// 提交套路表单
async function saveAndContinue() {
  if (!eventForm.value.routineName) {
    ElMessage.error('请输入套路名称');
    return;
  }
  const routine = {
    memo: eventForm.value.routineName,
    teamId: teamStore.teamGroupId,
    projectId: eventForm.value.projectName,
    userId: eventForm.value.participants
  };

  try {
    const response = await axios.post(`http://back1.idcfengye.com:15173/routine/teamproject`, routine, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    routineId.value = response.data.data;
  } catch (error) {
    if (error.response && error.response.status !== 200) {
      ElMessage.error(`填报失败: ${error.response.data.msg}`);
      return;
    }
  }

  try {
    // 为每个参与者创建数据对象并发送POST请求
    for (const participantId of eventForm.value.participants) {
      const data = {
        routineid: routineId.value,
        teamId: teamStore.teamGroupId,
        projectId: eventForm.value.projectName,
        userId: participantId
      };

      // 发送POST请求
      const response = await axios.post(`http://back1.idcfengye.com:15173/teamgroup/memo`, data, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.status === 200 || response.data.success) {
        ElMessage.success('填报成功');
      }
    }
  } catch (error) {
    if (error.response && error.response.status !== 200) {
      ElMessage.error(`填报失败: ${error.response.data.msg}`);
    }
  }
}
</script>

<style scoped>
.box-card {
  padding: 30px;
  padding-bottom: 0%;
  background-color: #a3c9c7;
  width: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 30px;
}

.event-form {
  margin-bottom: 20px;
}
.body{
  display: flex;
  justify-content: center;
  align-items: center;
}
.main{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
span {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  text-align: center;
  margin-bottom: 20px;
}
</style>